<style scoped lang="scss">
.AMapContainer-bg {
  width: 100%;
  position: absolute;
  top: 0;
  bottom: 0;
  z-index: 0 !important;
}

.AMapContainer-district-list {
  .el-breadcrumb {
    span {
      cursor: pointer;
      color: rgba(255, 255, 255, 0.9);
      font-size: 16px;
    }

    span:hover {
      color: rgba(43, 241, 236, 1);
    }
  }

  .district-list {
    background: rgba(255, 255, 255, 0.3);
    div.district-item {
      display: inline-block;
      border: 1px solid rgba(255, 255, 255, 0.9);
      margin: 5px;
      padding: 1px 5px;
      color: rgba(255, 255, 255, 0.9);
      cursor: pointer;
    }

    div.district-item:hover {
      border: 1px solid rgba(43, 241, 236, 1);
      color: rgba(43, 241, 236, 1);
    }
  }
}
</style>
<template>
  <div>
    <!-- 地图作为背景图 -->
    <div id="AMapContainer" class="AMapContainer-bg"></div>

    <!-- 右侧内容栏 background-color: red;-->
    <div
      style="
        position: absolute;
        right: 10px;
        width: 340px;
        top: 300px;
        bottom: 5px;
      "
    >
      <slot name="mapRightCenterContainer"></slot>

      <!-- 行政区域 选择面板 -->
      <div
        v-loading="loading"
        class="AMapContainer-district-list"
        style="height: 100%; margin-top: 5px;"
      >
        <el-row
          style="
            height: 40px;
            line-height: 40px;
            padding: 0 10px;
            background: rgba(255, 255, 255, 0.3);
            -webkit-box-shadow: 0px 0px 10px rgb(255 255 255 / 40%) inset;
            box-shadow: 0px 0px 10px rgb(255 255 255 / 40%) inset;
          "
        >
          <el-breadcrumb separator="/" style="margin-top: 12px">
            <el-breadcrumb-item
              v-for="(item, index) of DistrictList"
              :key="index"
            >
              <span @click="changeDistrictSearch(item, index)">{{
                item.districtName
              }}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </el-row>

        <el-row class="district-list" style="height: 100%">
          <template v-for="(item, index) of DistrictSearch.districtList">
            <div
              :key="index"
              class="district-item"
              @click="changeDistrictSearch(item, -1)"
            >
              {{ item.name }}
            </div>
          </template>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import store from "@/store";
import AMapLoader from "@amap/amap-jsapi-loader";
import BigDataCard from "@/views/bigData/components/Card-1.vue";

//
import { getDept } from "@/api/system/dept";
// 引入疫情数据
import { yiqingChinaData } from "./data/yiqing-data.js";
import { citiesData } from "./data/yiqing-cities.js";

import { schoolData } from "./data/school-position.js";

export default {
  name: "AMapContainerBg1",
  components: { BigDataCard },
  data() {
    return {
      loading: false,
      aMap: null,
      GaoDe: {
        key: "034784b56322364d3dda15a51216b2db",
        secret: "86e258a1df3adcf436d4584c0132886c",
        version: "2.0",
        mapId: "190ec250626f4fdb5fad51d3e638caac",
      },
      DistrictList: [],
      /** 2. 行政区域查询 **/
      DistrictSearch: {
        // level: "province", districtCode: "340000", districtName: "安徽省",
        // level: "province", districtCode: "370000", districtName: "山东省",
        // level: "city", districtCode: "370700", districtName: "潍坊市",
        // level: "district", districtCode: "370782", districtName: "诸城市",
        // level: "district", districtCode: "370781", districtName: "青州市",
        level: "country",
        districtCode: "",
        districtName: "",
        districtList: [],
      },
      district: null,
      polygons: [], // 电子围栏边界

      /** 3. 标注和标注图层 **/
      markers: [],
      cityNames: [],

      /** 4. 简易行政区域 **/
      showDistrictLayer: false, // 是否显示简易行政区域
      DistrictLayer: {},
      // 创建省份图层
      disProvince: null,
      layerColors: {},
    };
  },
  props: {
    deptId: {
      type: String | Number,
      default: store.state.user.deptId,
    },
    markerType: {
      type: String, default: null,
    },
  },
  created() {
    this.initDept();
    this.initAMapLoader();
  },
  methods: {
    /**
     * 0. 初始化部门信息
     */
    async initDept() {
      let that = this;
      this.DistrictList = [];

      var rootDeptCookieKey =
        "User-root-dept-cookie-key-" + this.$store.state.user.userId;
      var rootDeptCookieValue = Cookies.get(rootDeptCookieKey);
      if (this.$yhFunc.isEmpty(rootDeptCookieValue)) {
        await getDept(this.deptId).then((response) => {
          rootDeptCookieValue = {
            level: response.data.deptLevel || this.DistrictSearch.level,
            districtCode:
              response.data.deptId + "" || this.DistrictSearch.districtCode,
            districtName:
              response.data.deptName || this.DistrictSearch.districtName,
          };
          this.DistrictSearch = rootDeptCookieValue;
          this.DistrictList.push(this.$yhFunc.deepClone(rootDeptCookieValue));
          Cookies.set(rootDeptCookieKey, JSON.stringify(rootDeptCookieValue), {
            expires: 1,
          }); // 默认保存7天
        });
      } else {
        rootDeptCookieValue = JSON.parse(rootDeptCookieValue);
        this.DistrictSearch = rootDeptCookieValue;
        this.DistrictList.push(this.$yhFunc.deepClone(rootDeptCookieValue));
      }
    },

    /**
     * 1. 初始化地图加载器
     * 安徽省坐标 [117.330139,31.734559]
     */
    async initAMapLoader() {
      let that = this;
      that.loading = true;
      window._AMapSecurityConfig = { securityJsCode: that.GaoDe.secret }; // 配置高德秘钥
      await AMapLoader.load({
        key: that.GaoDe.key, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: that.GaoDe.version, // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          // 0. 初始化地图
          that.aMap = new AMap.Map("AMapContainer", {
            zoom: 7,
            mapStyle: "amap://styles/" + that.GaoDe.mapId, // 自定义 map 样式
            pitch: 0,
            viewMode: "3D",

            showIndoorMap: false, // 是否显示室内地图 
            // showLabel: false, // 是否显示个地方的地名 
          });

          //异步同时加载多个插件
          AMap.plugin(
            ["AMap.DistrictSearch", "AMap.DistrictLayer", "AMap.PlaceSearch"],
            function () {
              // 2. 行政区域查询
              that.handleDistrictSearch();
              // // 4. 简易行政区域
              // if (that.showDistrictLayer) {
              //   // 是否显示简易行政区域
              //   that.handleDistrictLayer();
              // }
            }
          );
          // 3. 标注和标注图层
          if(that.markerType == 'index'){
            that.handleMarkersLayer();
          }else if(that.markerType == 'school'){
            that.handlePositionMarker();
          }
          
        })
        .catch((e) => {
          console.log(e);
        });
    },

    /**
     * ***************************************************************
     * 3. 行政区域查询
     * ***************************************************************
     */
    handleDistrictSearch() {
      let that = this;
      that.district = new AMap.DistrictSearch({
        //实例化DistrictSearch
        level: that.DistrictSearch.level,
        subdistrict: 1, // 返回下一级行政区
        extensions: "all", // 'all' or 'false' 是否返回行政区边界坐标点
        showbiz: true, //最后一级返回街道信息
      });
      // 查询的名称
      var searchName =
        that.DistrictSearch.districtCode || that.DistrictSearch.districtName;
      that.district.search(searchName, function (status, result) {
        if (status == "complete") {
          var currDistrict = result.districtList[0];
          that.DistrictSearch.districtList = currDistrict.districtList;
          that.getDistrictSearchData(currDistrict);
          that.loading = false;
          // console.log('下一级行政列表', currDistrict.districtList);
          // for(var item of currDistrict.districtList){
          //   console.log(item.name + '  --  ' + item.adcode)
          // }
        } else {
          return that.$modal.msg("行政区域查询错误");
        }
      });
    },
    getDistrictSearchData(data, level) {
      let that = this;
      var bounds = data.boundaries;
      if (bounds) {
        for (var i = 0, l = bounds.length; i < l; i++) {
          var polygon = new AMap.Polygon({
            map: that.aMap,
            strokeWeight: 1,
            strokeColor: "#0091ea",
            fillColor: "#80d8ff",
            fillOpacity: 0.2,
            path: bounds[i],
          });
          that.polygons.push(polygon);
        }
        that.aMap.setFitView(); //地图自适应
      }
    },

    /**
     * ***************************************************************
     * 4. 标注和标注图层
     * ***************************************************************
     */
    handleMarkersLayer() {

      let that = this; 
      that.markers = [];
      var layer = new AMap.LabelsLayer({
        zooms: [3, 20],
        zIndex: 1000,
        collision: false,
        allowCollision: false,
      });
      layer.add(that.markers);
      // 图层添加到地图
      that.aMap.add(layer);

      var textStyle = {
        fontSize: 12,
        fontWeight: "normal",
        fillColor: "#fff",
        padding: "2, 5",
        backgroundColor: "rgb(246,137,38)",
        borderColor: "#fff",
        borderWidth: 1,
      };
      
      //
      var _prefix = {
        2: this.DistrictSearch.districtCode.substring(0, 2),
        4: this.DistrictSearch.districtCode.substring(0, 4),
        6: this.DistrictSearch.districtCode.substring(0, 6),
      };
      

      // 初始化 labelMarker
      /** 省级部署 */
      var provinces = yiqingChinaData.provinces || [];
      for (var province of provinces) {

        var province_prefix = province.id.substring(0, 2);
        if (province_prefix != _prefix[2]) continue;
        // console.log('当前省份：', province)

        var cities = province.cities || [];
        if(cities.length <= 0) that.$modal.msg('暂无数据分布');
        for (var city of cities) { 
          // 省级：显示市
          if(this.DistrictSearch.level == 'province'){
            that.setMarkerLayer(city, textStyle);
            continue;
          }

          /** 市级部署  */ 
          var city_prefix = city.id.substring(0, 4);
          if(city_prefix != _prefix[4]) continue;
          // console.log('当前城市：', city);

          var districts = city.districts || [];
          if(districts.length <= 0) that.$modal.msg('暂无数据分布');
          for(var district of districts){ 
            // 市级：显示区县 
            if(this.DistrictSearch.level == 'city'){ 
              that.setMarkerLayer(district, textStyle); 
              continue; 
            } 

            /** 区县级部署 */ 
            var district_prefix = district.id.substring(0, 6);
            if(district_prefix != _prefix[6]) continue;
            // console.log('当前区县：', district);

            var streets = district.streets || [];
            if(streets.length <= 0) that.$modal.msg('暂无数据分布');
            for(var street of streets){
              if(this.DistrictSearch.level == 'district'){
                that.setMarkerLayer(street, textStyle);
                continue;
              }
            }
          }
        }
      }

      layer.add(that.markers);
    },
    findInRegions(id) {
      for (const city of citiesData) {
        if (id === city.adcode) {
          return city;
        }
      }
    },
    // 根据数据多少，获取 颜色
    getColorByNumber(number) {
      var colorLegend = {
        10: "#f9c02f",
        100: "#f5a54f",
        500: "#f18334",
        1000: "#cc5f42",
        5000: "#a94d36",
        100000: "#792a17",
      };
      var color;
      for (var key in colorLegend) {
        if (colorLegend.hasOwnProperty(key)) {
          if (number < parseInt(key)) {
            color = colorLegend[key]; 
            break; 
          } 
        } 
      } 
      return color; 
    }, 
    setMarkerLayer(city, textStyle){ 
      let that = this;
      var curCityData = that.findInRegions(city.id);
      var number = city.confirmedNum;

      if(curCityData && number){
        textStyle.backgroundColor = that.getColorByNumber(number); // 根据数据加载背景色
        var marker = new AMap.LabelMarker({
          name: city.name,
          position: [curCityData.x, curCityData.y],
          zIndex: number,
          text: {
            content: city.name + ": " + city.confirmedNum,
            direction: "center",
            style: textStyle,
          },
        });
        that.markers.push(marker);
      }

    },

    /**
     * ***************************************************************
     * 5. 学校标注点 
     * ***************************************************************
     */
    handlePositionMarker(){
      let that = this;
      var markerIcon = new AMap.Icon({
        // 图标的取图地址
        // image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
        image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
        // 图标尺寸
        size: new AMap.Size(40, 40),
        // 图标所用图片大小
        imageSize: new AMap.Size(20, 30),
      });
      
      var schoolList = [];
      for(var school of schoolData){
        var prefix = 0;

        switch(that.DistrictSearch.level){
          case 'province':
            prefix = 2;
          break;
          case 'city': 
            prefix = 4;
          break;
          case 'district': 
            prefix = 6;
          break;
          default: break;
        }

        if(that.DistrictSearch.districtCode.substring(0, prefix) == school.id.substring(0, prefix)){
          schoolList.push(school);
        }
      }

      for(var school of schoolList){
        var positionMarker = new AMap.Marker({
          position: school.lngLat,
          icon: markerIcon,
          anchor:'bottom-center',
          offset: new AMap.Pixel(0, 0),
          title: school.name
        })
        positionMarker.setMap(that.aMap);
      }
    },

    /**
     * ***************************************************************
     * 9. 通用方法
     * ***************************************************************
     */
    // 切换行政区域
    changeDistrictSearch(item, index) {
      // 0.
      var district = {
        level: item.level,
        districtCode: item.adcode || item.districtCode,
        districtName: item.name || item.districtName,
      };
      if (district.districtCode == this.DistrictSearch.districtCode) {
        console.log("相等不加载");
        return;
      }
      // 1. 加载地图
      this.DistrictSearch.level = district.level;
      this.DistrictSearch.districtCode = district.districtCode;
      this.DistrictSearch.districtName = district.districtName;
      // 2. 更新顶部面包屑
      var DistrictList = this.$yhFunc.deepClone(this.DistrictList);
      if (index < 0) {
        DistrictList.push(district);
        this.DistrictList = DistrictList;
      } else {
        var newList = DistrictList.slice(0, index + 1);
        this.DistrictList = newList;
      }
      this.initAMapLoader();
    },

    /**
     * ***************************************************************
     * 10. 其他方法
     * ***************************************************************
     */
    handleDistrictLayer() {
      let that = this;
      that.disProvince = new AMap.DistrictLayer.Province({
        zIndex: 12,
        adcode: [that.DistrictSearch.districtCode],
        depth: 1,
        styles: {
          fill: function (properties) {
            console.log("properties", properties);
            // properties为可用于做样式映射的字段，包含
            // NAME_CHN:中文名称
            // adcode_pro
            // adcode_cit
            // adcode
            var adcode = properties.adcode;
            return that.getColorByAdcode(adcode);
          },
          "province-stroke": "cornflowerblue",
          "city-stroke": "white", // 中国地级市边界
          "county-stroke": "rgba(255,255,255,0.5)", // 中国区县边界
        },
      });
      that.disProvince.setMap(that.aMap);
    },
    getColorByAdcode(adcode) {
      let that = this;
      if (!that.layerColors[adcode]) {
        var gb = Math.random() * 155 + 50;
        that.layerColors[adcode] = "rgba(" + gb + "," + gb + ",255,1)";
      }
      return that.layerColors[adcode];
    },
  },
};
</script>




